package com.guigu.auth.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.auth.entity.AuthUser;
import com.guigu.auth.entity.dto.AuthUserDTO;
import com.guigu.auth.entity.vo.AuthUserVO;
import com.guigu.auth.service.AuthUserService;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author TaoLong
 * @since 2021-12-06
 */
@RestController
@RequestMapping("/auth/auth-user")
@Api(tags = "用户管理")
@CacheConfig(cacheNames = {"authResource", "authMenu"})
public class AuthUserController {
    @Autowired
    private AuthUserService authUserService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 添加用户
     *
     * @param authUserDTO
     * @return
     */
    @ApiOperation("添加用户")
    @ApiImplicitParam(name = "authUserDTO", value = "认证用户对象")
    @PostMapping("/")
    public R addAuthUser(@RequestBody AuthUserDTO authUserDTO) {
        if (ObjectUtils.isEmpty(authUserDTO)) {
            throw new TmsException(ResultCode.ERROR_CODE, "对象为空!");
        }
        if (StringUtils.isBlank(authUserDTO.getCode())) {
            throw new TmsException(ResultCode.ERROR_CODE, "验证码为空!");
        }
        if (!String.valueOf(redisTemplate.opsForValue().get(authUserDTO.getMobile())).equals(authUserDTO.getCode())) {
            throw new TmsException(ResultCode.ERROR_CODE, "验证码不正确!");
        }
        AuthUser authUser = new AuthUser();
        BeanUtils.copyProperties(authUserDTO, authUser);
        /**
         * 对密码进行BCrypt加密
         */
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(authUser.getPassword());
        authUser.setPassword(password);
        /**
         * 设置创建时间
         */
        authUser.setCreateTime(new Date());
        authUserService.save(authUser);
        return new R(ResultCode.SUCCESS_CODE, "添加用户成功!", true);
    }

    /**
     * 分页查询用户信息
     *
     * @param pageNum  页码
     * @param pageSize 页数
     * @return
     */
    @ApiOperation("分页查询用户信息")
    @GetMapping("/findPage/{pageNum}/{pageSize}")
    public R<IPage<AuthUser>> findPage(@PathVariable String pageNum,
                                       @PathVariable String pageSize) {

        IPage<AuthUser> authUserIPage = new Page<AuthUser>();
        if (StringUtils.isBlank(pageNum) || !StringUtils.isNumeric(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isBlank(pageSize) || !StringUtils.isNumeric(pageSize)) {
            pageSize = "5";
        }
        authUserIPage.setSize(Long.parseLong(pageSize));
        authUserIPage.setCurrent(Long.parseLong(pageNum));
        IPage<AuthUser> page = authUserService.page(authUserIPage, null);
        return new R<>(ResultCode.SUCCESS_CODE, page);
    }


    /**
     * 根据token查询出其对应的用户信息
     *
     * @param token 令牌
     * @return
     */
    @ApiOperation("根据token查询出其对应的用户信息")
    @GetMapping("/findByToken")
    public R<AuthUserVO> findByToken(@RequestParam("token") String token) {
        return authUserService.findByToken(token);
    }


    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询用户")
    @GetMapping("/findAuthUserById/{id}")
    public R<AuthUserVO> findAuthUserById(@PathVariable String id) {
        AuthUser user = this.authUserService.getById(id);
        AuthUserVO authUserVO = new AuthUserVO();
        BeanUtils.copyProperties(user, authUserVO);
        return new R<>(ResultCode.SUCCESS_CODE, authUserVO);
    }


    /**
     * 根据id修改用户
     * @param authUserDTO
     * @return
     */
    @ApiOperation("根据id修改用户")
    @PutMapping("/updateUserById")
    @CacheEvict(allEntries = true)
    public R updateUserById(@RequestBody AuthUserDTO authUserDTO){
        if (ObjectUtils.isEmpty(authUserDTO)) {
            throw new TmsException(ResultCode.ERROR_CODE, "对象为空!");
        }
        if (StringUtils.isNotBlank(authUserDTO.getCode())) {
            if (!String.valueOf(redisTemplate.opsForValue().get(authUserDTO.getMobile())).equals(authUserDTO.getCode())) {
                throw new TmsException(ResultCode.ERROR_CODE, "验证码不正确!");
            }
        }
        AuthUser authUser = new AuthUser();
        BeanUtils.copyProperties(authUserDTO, authUser);
        /**
         * 设置创建时间
         */
        authUser.setCreateTime(new Date());
        authUserService.updateById(authUser);
        return new R(ResultCode.SUCCESS_CODE, "修改用户成功!", true);
    }
}

